<template>
  <view class="edit-address-container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @tap="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">编辑地址</text>
    </view>

    <!-- 加载中 -->
    <uni-load-more v-if="loading" status="loading"></uni-load-more>

    <!-- 表单区域 -->
    <view v-else class="form-section">
      <view class="form-item">
        <text class="label">收货人</text>
        <uni-easyinput
          v-model="form.receiverName"
          placeholder="请输入收货人姓名"
          class="without-border"
        ></uni-easyinput>
      </view>

      <view class="form-item">
        <text class="label">手机号码</text>
        <uni-easyinput
          v-model="form.receiverPhone"
          type="number"
          placeholder="请输入手机号码"
          class="without-border"
          maxlength="11"
        ></uni-easyinput>
      </view>

      <view class="form-item">
        <text class="label">所在地区</text>
        <uni-data-picker
          v-model="form.region"
          :localdata="regionData"
          popup-title="请选择地区"
          @change="onRegionChange"
        ></uni-data-picker>
      </view>

      <view class="form-item">
        <text class="label">详细地址</text>
        <uni-easyinput
          v-model="form.detailAddress"
          type="textarea"
          placeholder="请输入详细地址，如街道、门牌号等"
          class="without-border"
        ></uni-easyinput>
      </view>

      <view class="form-item">
        <text class="label">邮政编码</text>
        <uni-easyinput
          v-model="form.postCode"
          placeholder="请输入邮政编码（选填）"
          class="without-border"
          type="number"
          maxlength="6"
        ></uni-easyinput>
      </view>

      <view class="form-item">
        <text class="label">地址标签</text>
        <uni-easyinput
          v-model="form.label"
          placeholder="请输入标签，如'家'、'公司'等（选填）"
          class="without-border"
        ></uni-easyinput>
      </view>

      <view class="form-item">
        <text class="label">设为默认地址</text>
        <switch
          :checked="form.isDefault"
          @change="(e) => form.isDefault = e.detail.value"
          color="#ff5500"
        ></switch>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn">
      <button type="primary" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script>
import api from '@/config/api'
import { mapUviewIconName } from '@/utils/icon-mapper.js'

export default {
  data() {
    return {
      addressId: '',
      loading: true,
      form: {
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        region: '',
        detailAddress: '',
        postCode: '',
        label: '家',
        isDefault: false
      },
      regionData: []
    }
  },

  onLoad(options) {
    if (options.id) {
      this.addressId = options.id
      this.loadAddressDetail()
    } else {
      this.loading = false
    }
    this.loadRegionData()
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    async loadAddressDetail() {
      try {
        const res = await this.$api.user.address.detail(this.addressId)
        if (res.code === 200) {
          const address = res.data
          this.form = {
            receiverName: address.receiverName,
            receiverPhone: address.receiverPhone,
            province: address.province,
            city: address.city,
            district: address.district,
            provinceCode: address.provinceCode,
            cityCode: address.cityCode,
            districtCode: address.districtCode,
            region: `${address.province} ${address.city} ${address.district}`,
            detailAddress: address.detailAddress,
            postCode: address.postCode || '',
            label: address.label || '家',
            isDefault: address.isDefault === 1
          }
        } else {
          throw new Error(res.message || '加载失败')
        }
      } catch (error) {
        console.error('加载地址详情失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        this.loading = false
      }
    },

    async loadRegionData() {
      try {
        const res = await this.$api.user.region.getRegionTree()
        if (res.code === 200) {
          this.regionData = this.formatRegionData(res.data)
        }
      } catch (error) {
        console.error('加载地区数据失败:', error)
        uni.showToast({
          title: '加载地区数据失败',
          icon: 'none'
        })
      }
    },

    formatRegionData(data) {
      // 转换后端返回的树形结构为 uni-data-picker 需要的格式
      return data.map(province => ({
        value: province.code,
        text: province.name,
        level: province.level,
        children: province.children?.map(city => ({
          value: city.code,
          text: city.name,
          level: city.level,
          children: city.children?.map(district => ({
            value: district.code,
            text: district.name,
            level: district.level
          }))
        }))
      }))
    },

    onRegionChange(e) {
      if (!e.detail.value || e.detail.value.length < 3) {
        return
      }
      
      const [province, city, district] = e.detail.value
      // 确保选择了完整的地区信息
      if (province && city && district) {
        this.form.province = province.text
        this.form.city = city.text
        this.form.district = district.text
        // 保存区域编码，用于提交到后端
        this.form.provinceCode = province.value
        this.form.cityCode = city.value
        this.form.districtCode = district.value
      }
    },

    validateForm() {
      if (!this.form.receiverName) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
        return false
      }
      if (!this.form.receiverPhone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return false
      }
      if (!/^1[3-9]\d{9}$/.test(this.form.receiverPhone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        })
        return false
      }
      if (!this.form.province || !this.form.city || !this.form.district) {
        uni.showToast({
          title: '请选择所在地区',
          icon: 'none'
        })
        return false
      }
      if (!this.form.detailAddress) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        })
        return false
      }
      return true
    },

    async handleSubmit() {
      if (!this.validateForm()) return

      try {
        // 构造请求数据
        const addressData = {
          receiverName: this.form.receiverName,
          receiverPhone: this.form.receiverPhone,
          province: this.form.province,
          city: this.form.city,
          district: this.form.district,
          provinceCode: this.form.provinceCode,
          cityCode: this.form.cityCode,
          districtCode: this.form.districtCode,
          detailAddress: this.form.detailAddress,
          postCode: this.form.postCode || '',
          label: this.form.label || '家',
          isDefault: this.form.isDefault ? 1 : 0
        }

        const res = await this.$api.user.address.update(this.addressId, addressData)
        if (res.code === 200) {
          // 如果设置为默认地址，调用设置默认地址接口
          if (this.form.isDefault && res.data) {
            await api.user.setDefaultAddress(this.addressId)
          }

          uni.showToast({
            title: '更新成功',
            icon: 'success'
          })
          
          // 通知上一页刷新数据
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          if (prevPage && prevPage.$vm) {
            // 设置上一页的需要刷新标志
            prevPage.$vm.needRefresh = true
          }
          
          // 延迟返回，确保用户能看到成功提示
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            })
          }, 1500)
        } else {
          throw new Error(res.message || '更新失败')
        }
      } catch (error) {
        console.error('更新地址失败:', error)
        uni.showToast({
          title: error.message || '更新失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-address-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #ffffff;

  .nav-back {
    padding: 20rpx;
    margin-left: -20rpx;
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    color: #333;
    margin-right: 44rpx;
  }
}

.form-section {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
  border-radius: 12rpx;

  .form-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    &:last-child {
      border-bottom: none;
    }

    .label {
      width: 140rpx;
      font-size: 28rpx;
      color: #333;
    }

    .uni-easyinput {
      flex: 1;
    }
  }
}

.submit-btn {
  margin: 40rpx 30rpx;
}
</style> 